package com.tools.sys.controller;

import com.tools.common.core.model.Result;
import com.tools.common.core.util.CheckResult;
import com.tools.common.core.util.JwtUtils;
import com.tools.sys.entity.SysMenu;
import com.tools.sys.repository.SysMenuRepository;
import com.tools.sys.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 菜单管理
 * 爪哇笔记：https://blog.52itstyle.vip
 */
@Api(tags ="菜单管理")
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysMenuRepository sysMenuRepository;

    /**
     * 列表
     */
    @ApiOperation(value="菜单列表")
    @PostMapping("/list")
    public Result list(SysMenu menu){
        return sysMenuService.list(menu);
    }

    /**
     * 树结构
     */
    @ApiOperation(value="树结构菜单")
    @PostMapping("/select")
    public Result select(Long parentId){
        List<SysMenu> list = sysMenuService.select(parentId);
        return Result.ok(list);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation(value="保存菜单")
    public Result save(@RequestBody SysMenu menu){
        sysMenuRepository.saveAndFlush(menu);
        return Result.ok("保存成功");
    }

    /**
     * 删除
     */
    @ApiOperation(value="删除菜单")
    @PostMapping("/delete")
    public Result delete(Long menuId){
        return sysMenuService.delete(menuId);
    }


    /**
     * 获取菜单
     */
    @ApiOperation(value="根据用户信息获取菜单")
    @PostMapping("/getByUser")
    public List<SysMenu> getByUser(HttpServletRequest request){
        String token = request.getHeader("token");
        if(StringUtils.isNotBlank(token)){
            CheckResult result = JwtUtils.validateJWT(token);
            if(result.isSuccess()){
                String userId = result.getClaims().getId();
                return sysMenuService.getByUserId(Long.parseLong(userId));
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * 拖动菜单
     */
    @ApiOperation(value="树结构拖动菜单")
    @PostMapping("/drop")
    public Result drop(Long parentId,Long menuId){
        return sysMenuService.drop(parentId,menuId);
    }
}
